﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.InterferenceVolumeQuery.CApIVQManager
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.InterferenceVolumeQuery.Resources;
using EngineeringInternalExtension;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Media;
using Tecnomatix.Engineering;


namespace DnProcessSimulateCommands.InterferenceVolumeQuery;

internal class CApIVQManager
{
  private static string currentHighLightedIV = "";
  private static Dictionary<ITxObject, List<TxNote>> createdNotes = new Dictionary<ITxObject, List<TxNote>>();
  private static TxObjectList locationsSnapshot = new TxObjectList();
  private static TxDisplayableObjectsUtilsEx objUtils = new TxDisplayableObjectsUtilsEx();
  private static TxColor SWEPT_VOLUME1_HIERARCHY_COLOR = new TxColor(byte.MaxValue, byte.MaxValue, (byte) 0);
  private static TxColor SWEPT_VOLUME2_HIERARCHY_COLOR = new TxColor((byte) 87, (byte) 192 /*0xC0*/, byte.MaxValue);
  private static TxColor INTERFERENCE_VOLUME_COLOR = new TxColor((byte) 229, (byte) 15, (byte) 15);
  private static TxColor SWEPT_VOL1_NOTES_COLOR = new TxColor(byte.MaxValue, byte.MaxValue, (byte) 10);
  private static TxColor SWEPT_VOL2_NOTES_COLOR = new TxColor((byte) 125, (byte) 239, byte.MaxValue);
  private static TxColorEmphasizePriority EMPHASIZE_PRIORITY = (TxColorEmphasizePriority) 3;
  private static double SWEPT_VOLUME_TRANSPARENCY = 0.2;
  private static TxObjectList blankedObjects = new TxObjectList();
  private static TxObjectList displayedObjects = new TxObjectList();

  private static TxColor GetColorWithTransparency(TxColor col, double transp)
  {
    return new TxColor(col.Red, col.Green, col.Blue, transp);
  }

  private static TxObjectList GetSweptVolumes(ITxObject obj)
  {
    TxObjectList sweptVolumes = new TxObjectList();
    if (obj is ITxSweptVolumeHoldingObject volumeHoldingObject)
      sweptVolumes = volumeHoldingObject.SweptVolumes;
    return sweptVolumes;
  }

  private static ITxRobot GetRobot(ITxObject obj)
  {
    ITxRobot robot = (ITxRobot) null;
    if (obj != null)
    {
      if (obj is ITxRoboticOrderedCompoundOperation)
        robot = (obj as ITxRoboticOrderedCompoundOperation).Robot;
      if (obj is ITxRoboticProgram)
        robot = (obj as ITxRoboticProgram).Robot;
    }
    return robot;
  }

  private static ImageSource GetImage(ITxObject obj)
  {
    return TxIconManager.the().GetObjectImageSource(obj);
  }

  private static void GetBlankAndDisplayNecessaryObjects(
    TxObjectList displayedSV,
    ITxDisplayableObject IV)
  {
    List<TxNote> txNoteList = new List<TxNote>();
    foreach (ITxObject key in CApIVQManager.createdNotes.Keys)
    {
      if (key != IV)
      {
        foreach (ITxObject itxObject in CApIVQManager.createdNotes[key])
          ((Collection<ITxObject>) CApIVQManager.blankedObjects).Add(itxObject);
      }
    }
    TxObjectList allDescendants = TxApplication.ActiveDocument.PhysicalRoot.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (TxSweptVolume)));
    foreach (ITxObject itxObject in (Collection<ITxObject>) displayedSV)
    {
      ((Collection<ITxObject>) allDescendants).Remove(itxObject);
      if (itxObject is ITxDisplayableObject displayableObject && displayableObject.Visibility == 2)
        ((Collection<ITxObject>) CApIVQManager.displayedObjects).Add((ITxObject) displayableObject);
    }
    foreach (ITxDisplayableObject displayableObject in (Collection<ITxObject>) allDescendants)
    {
      if (displayableObject.Visibility == null)
        ((Collection<ITxObject>) CApIVQManager.blankedObjects).Add((ITxObject) displayableObject);
    }
    foreach (ITxObject blankedObject in (Collection<ITxObject>) CApIVQManager.blankedObjects)
    {
      if (blankedObject is ITxDisplayableObject)
        (blankedObject as ITxDisplayableObject).Blank();
    }
    if (IV.Visibility == 2)
      ((Collection<ITxObject>) CApIVQManager.displayedObjects).Add((ITxObject) IV);
    if (((Collection<ITxObject>) CApIVQManager.blankedObjects).Count > 0)
      TxGraphicsUtilitiesEx.BlankObjects(CApIVQManager.blankedObjects, true);
    if (((Collection<ITxObject>) CApIVQManager.displayedObjects).Count <= 0)
      return;
    TxGraphicsUtilitiesEx.DisplayObjects(CApIVQManager.displayedObjects, true);
  }

  private static void AddNoteToDict(ITxObject ivObj, ITxObject assignedObj, TxNote note)
  {
    if (!CApIVQManager.createdNotes.ContainsKey(ivObj))
      CApIVQManager.createdNotes[ivObj] = new List<TxNote>();
    CApIVQManager.createdNotes[ivObj].Add(note);
  }

  private static void CreateNote(
    string noteNamePrefix,
    string Text,
    ITxLocatableObject assignedTo,
    TxInterferenceVolume iv)
  {
    TxPhysicalRoot physicalRoot = TxApplication.ActiveDocument.PhysicalRoot;
    TxNoteCreationDataEx noteCreationDataEx = new TxNoteCreationDataEx(physicalRoot.GetUniqueDisplayName(noteNamePrefix), assignedTo);
    TxNote note = physicalRoot.CreateNote((TxNoteCreationData) noteCreationDataEx);
    note.Text = Text;
    CApIVQManager.AddNoteToDict((ITxObject) iv, (ITxObject) assignedTo, note);
  }

  private static void AddObjectsIntoDictWithColor(
    List<IIVQTreeViewItem> objects,
    Dictionary<ITxDisplayableObject, TxColor> dict,
    TxColor col,
    List<TxNote> possibleNotes,
    TxColor notesColor)
  {
    foreach (IIVQTreeViewItem ivqTreeViewItem in objects)
    {
      if (ivqTreeViewItem.IVQObject is ITxDisplayableObject ivqObject1 && !dict.Keys.Contains<ITxDisplayableObject>(ivqObject1))
      {
        if (ivqObject1 is TxSweptVolume)
          dict.Add(ivqObject1, CApIVQManager.GetColorWithTransparency(col, CApIVQManager.SWEPT_VOLUME_TRANSPARENCY));
        else
          dict.Add(ivqObject1, col);
      }
      if (ivqTreeViewItem.IVQObject is ITxLocatableObject ivqObject2)
      {
        foreach (ITxObject attachmentDescendant in (Collection<ITxObject>) ivqObject2.GetDirectAttachmentDescendants((ITxTypeFilter) new TxTypeFilter(typeof (TxNote))))
        {
          if (possibleNotes.Contains(attachmentDescendant as TxNote) && !dict.Keys.Contains<ITxDisplayableObject>(attachmentDescendant as ITxDisplayableObject))
            dict.Add(attachmentDescendant as ITxDisplayableObject, notesColor);
        }
      }
    }
  }

  private static void CollectChildren(IIVQTreeViewItem rootNode, List<IIVQTreeViewItem> children)
  {
    if (rootNode.Children == null || rootNode.Children.Count <= 0)
      return;
    children.AddRange((IEnumerable<IIVQTreeViewItem>) rootNode.Children);
    foreach (IIVQTreeViewItem child in (Collection<IIVQTreeViewItem>) rootNode.Children)
      CApIVQManager.CollectChildren(child, children);
  }

  private static double GetAccumulatedTimeInRoboticProgram(
    ITxLocationOperation locOper,
    ITxObject opPr)
  {
    double inRoboticProgram = 0.0;
    TxRoboticProgram txRoboticProgram = opPr as TxRoboticProgram;
    ITxCompoundOperation roboticOperation1 = (locOper as ITxRoboticLocationOperation).ParentRoboticOperation as ITxCompoundOperation;
    for (int index = 0; index < txRoboticProgram.Count; ++index)
    {
      ITxRoboticProgramElement elementAt = txRoboticProgram.GetElementAt(index);
      if (elementAt is ITxOperation)
      {
        if (!((ITxObject) elementAt).Equals((object) roboticOperation1))
          inRoboticProgram += (elementAt as ITxOperation).Duration;
        else
          break;
      }
    }
    if (locOper is ITxRoboticLocationOperation locationOperation)
    {
      ITxCompoundOperation roboticOperation2 = locationOperation.ParentRoboticOperation as ITxCompoundOperation;
      inRoboticProgram += roboticOperation2.GetChildOperationRelativeStartTime((ITxOperation) locOper);
    }
    return inRoboticProgram;
  }

  private static double GetAccumulatedTimeInRoboticOperation(ITxLocationOperation locOper)
  {
    double roboticOperation = 0.0;
    if (locOper is ITxRoboticLocationOperation locationOperation)
    {
      ITxCompoundOperation compoundOperation = ((ITxObject) locationOperation).Collection as ITxCompoundOperation;
      roboticOperation += compoundOperation.GetChildOperationRelativeStartTime((ITxOperation) locOper);
      while (compoundOperation != null)
      {
        ITxObjectCollection collection = ((ITxObject) compoundOperation).Collection;
        if (collection != null && collection is ITxCompoundOperation)
        {
          roboticOperation += (collection as ITxCompoundOperation).GetChildOperationRelativeStartTime((ITxOperation) compoundOperation);
          compoundOperation = collection as ITxCompoundOperation;
          collection = (ITxObjectCollection) (((ITxObject) collection).Collection as ITxCompoundOperation);
        }
        if (collection is TxOperationRoot)
          break;
      }
    }
    return roboticOperation;
  }

  private static IVQTreeItem CreateParentOperation(
    ITxLocationOperation locationOperation,
    Dictionary<ITxObject, IVQTreeItem> parentOperations)
  {
    IVQTreeItem parentOperation = (IVQTreeItem) null;
    if (locationOperation is ITxRoboticLocationOperation locationOperation1)
    {
      if (parentOperations.ContainsKey((ITxObject) locationOperation1.ParentRoboticOperation))
      {
        parentOperation = parentOperations[(ITxObject) locationOperation1.ParentRoboticOperation];
      }
      else
      {
        parentOperation = new IVQTreeItem(((ITxObject) locationOperation1.ParentRoboticOperation).Name, (string) null, (string) null, (string) null, (ITxObject) locationOperation1.ParentRoboticOperation, (ObservableCollection<IIVQTreeViewItem>) null, CApIVQManager.GetImage((ITxObject) locationOperation1.ParentRoboticOperation));
        parentOperations.Add((ITxObject) locationOperation1.ParentRoboticOperation, parentOperation);
      }
    }
    return parentOperation;
  }

  private static string GetNoteMsg(TxInterferenceVolume iv, TxInterferenceVolumeLocationDataEx ivld)
  {
    string str = "";
    switch ((int) ivld.LocationType)
    {
      case 0:
        str = IVQResources.IVQ_LAST_LOC_BEFORE;
        break;
      case 1:
        str = IVQResources.IVQ_FIRST_LOC_AFTER;
        break;
      case 2:
        str = IVQResources.IVQ_FIRST_LOC_IN;
        break;
      case 3:
        str = IVQResources.IVQ_LAST_LOC_IN;
        break;
    }
    return $"{str} {iv.Name}";
  }

  private static void ShowAndSaveLocationVisState(ITxDisplayableObject obj)
  {
    if (obj == null || obj.Visibility == null)
      return;
    if (obj.Visibility == 2)
    {
      ((Collection<ITxObject>) CApIVQManager.locationsSnapshot).Add((ITxObject) obj);
    }
    else
    {
      foreach (ITxDisplayableObject allDescendant in (Collection<ITxObject>) ((ITxObjectCollection) (obj as ITxCompoundOperation)).GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxDisplayableObject))))
      {
        if (allDescendant.Visibility == 2)
          ((Collection<ITxObject>) CApIVQManager.locationsSnapshot).Add((ITxObject) allDescendant);
      }
    }
    if (((Collection<ITxObject>) CApIVQManager.locationsSnapshot).Count <= 0)
      return;
    TxGraphicsUtilitiesEx.DisplayObjects(CApIVQManager.locationsSnapshot, true);
  }

  public static void RemoveNote(ITxObject ivObj)
  {
    if (CApIVQManager.createdNotes.ContainsKey(ivObj))
    {
      foreach (TxNote txNote in CApIVQManager.createdNotes[ivObj])
        txNote.Delete();
      CApIVQManager.createdNotes.Remove(ivObj);
    }
    TxApplication.RefreshDisplay();
  }

  public static void RemoveAllNotes()
  {
    foreach (ITxObject key in CApIVQManager.createdNotes.Keys)
    {
      foreach (TxNote txNote in CApIVQManager.createdNotes[key])
        txNote.Delete();
    }
    CApIVQManager.createdNotes.Clear();
    TxApplication.RefreshDisplay();
  }

  public static List<IIVQTreeViewItem> CreateTreeViewItems(TxObjectList ivObjs)
  {
    List<IIVQTreeViewItem> treeViewItems = new List<IIVQTreeViewItem>();
    foreach (ITxObject ivObj in (Collection<ITxObject>) ivObjs)
    {
      TxInterferenceVolume iv = ivObj as TxInterferenceVolume;
      if (!TxInterferenceVolume.op_Equality(iv, (ITxObject) null))
      {
        TxObjectList holdingObjects = iv.HoldingObjects;
        IIVQTreeViewItem ivqTreeViewItem1 = (IIVQTreeViewItem) new IVQTreeItem(iv.Name, (string) null, (string) null, (string) null, (ITxObject) iv, (ObservableCollection<IIVQTreeViewItem>) null, CApIVQManager.GetImage((ITxObject) iv));
        foreach (ITxObject opPr in (Collection<ITxObject>) holdingObjects)
        {
          ITxRobot robot = CApIVQManager.GetRobot(opPr);
          TxObjectList sweptVolumes = CApIVQManager.GetSweptVolumes(opPr);
          TxSweptVolume txSweptVolume;
          if (sweptVolumes != null && ((Collection<ITxObject>) sweptVolumes).Count > 0)
          {
            txSweptVolume = ((IEnumerable<ITxObject>) sweptVolumes).ElementAt<ITxObject>(0) as TxSweptVolume;
            if (((Collection<ITxObject>) sweptVolumes).Count > 1 && (((IEnumerable<ITxObject>) sweptVolumes).ElementAt<ITxObject>(1) as TxSweptVolume).Clearance < txSweptVolume.Clearance)
              txSweptVolume = ((IEnumerable<ITxObject>) sweptVolumes).ElementAt<ITxObject>(1) as TxSweptVolume;
          }
          else
            txSweptVolume = (TxSweptVolume) null;
          IIVQTreeViewItem ivqTreeViewItem2 = !TxSweptVolume.op_Inequality(txSweptVolume, (ITxObject) null) ? (IIVQTreeViewItem) new IVQTreeItem(IVQResources.IVQ_MISSING_SWEPT_VOLUME, (string) null, (string) null, (string) null, (ITxObject) null, (ObservableCollection<IIVQTreeViewItem>) null, (ImageSource) null) : (IIVQTreeViewItem) new IVQTreeItem(txSweptVolume.Name, (string) null, (string) null, (string) null, (ITxObject) txSweptVolume, (ObservableCollection<IIVQTreeViewItem>) null, CApIVQManager.GetImage((ITxObject) txSweptVolume));
          IIVQTreeViewItem ivqTreeViewItem3 = robot == null ? (IIVQTreeViewItem) new IVQTreeItem(IVQResources.IVQ_MISSING_ROBOT, (string) null, (string) null, (string) null, (ITxObject) null, (ObservableCollection<IIVQTreeViewItem>) null, (ImageSource) null) : (IIVQTreeViewItem) new IVQTreeItem(((ITxObject) robot).Name, (string) null, (string) null, (string) null, (ITxObject) robot, (ObservableCollection<IIVQTreeViewItem>) null, CApIVQManager.GetImage((ITxObject) robot));
          ivqTreeViewItem2.Children.Add(ivqTreeViewItem3);
          IIVQTreeViewItem ivqTreeViewItem4 = (IIVQTreeViewItem) new IVQTreeItem(opPr.Name, (string) null, (string) null, (string) null, opPr, (ObservableCollection<IIVQTreeViewItem>) null, CApIVQManager.GetImage(opPr));
          ivqTreeViewItem2.Children.Add(ivqTreeViewItem4);
          List<TxInterferenceVolumeLocationDataEx> interferenceLocations = TxInterferenceVolumeEx.GetHoldingObjectInterferenceLocations(iv, opPr as ITxInterferenceVolumeHoldingObject);
          bool flag = opPr is ITxRoboticProgram;
          Dictionary<ITxObject, IVQTreeItem> parentOperations = new Dictionary<ITxObject, IVQTreeItem>();
          foreach (TxInterferenceVolumeLocationDataEx ivld in interferenceLocations)
          {
            if (flag)
            {
              if (ivld.Location is ITxRoboticLocationOperation)
                CApIVQManager.ShowAndSaveLocationVisState((ivld.Location as ITxRoboticLocationOperation).ParentRoboticOperation as ITxDisplayableObject);
            }
            else
              CApIVQManager.ShowAndSaveLocationVisState(opPr as ITxDisplayableObject);
            string noteMsg = CApIVQManager.GetNoteMsg(iv, ivld);
            CApIVQManager.CreateNote("Zone_" + opPr.Name, noteMsg, ivld.Location as ITxLocatableObject, iv);
            double num = Math.Round(flag ? CApIVQManager.GetAccumulatedTimeInRoboticProgram(ivld.Location, opPr) : CApIVQManager.GetAccumulatedTimeInRoboticOperation(ivld.Location), 2);
            IVQTreeItem ivqTreeItem = new IVQTreeItem(((ITxObject) ivld.Location).Name, num.ToString(), noteMsg, TxRoboticCommand.op_Equality(ivld.RoboticCommand, (ITxObject) null) ? "" : ivld.RoboticCommand.Text, (ITxObject) ivld.Location, (ObservableCollection<IIVQTreeViewItem>) null, CApIVQManager.GetImage((ITxObject) ivld.Location));
            if (flag)
            {
              IVQTreeItem parentOperation = CApIVQManager.CreateParentOperation(ivld.Location, parentOperations);
              if (parentOperation != null)
              {
                parentOperation.Children.Add((IIVQTreeViewItem) ivqTreeItem);
                if (!ivqTreeViewItem4.Children.Contains((IIVQTreeViewItem) parentOperation))
                  ivqTreeViewItem4.Children.Add((IIVQTreeViewItem) parentOperation);
              }
            }
            else
              ivqTreeViewItem4.Children.Add((IIVQTreeViewItem) ivqTreeItem);
          }
          ivqTreeViewItem1.Children.Add(ivqTreeViewItem2);
        }
        treeViewItems.Add(ivqTreeViewItem1);
      }
    }
    TxApplication.RefreshDisplay();
    return treeViewItems;
  }

  public static void HighLightObject(IIVQTreeViewItem obj)
  {
    Cursor current = Cursor.Current;
    Cursor.Current = Cursors.WaitCursor;
    if (obj == null)
      return;
    Dictionary<ITxDisplayableObject, TxColor> dict = new Dictionary<ITxDisplayableObject, TxColor>();
    ITxDisplayableObject ivqObject = obj.IVQObject as ITxDisplayableObject;
    List<IIVQTreeViewItem> ivqTreeViewItemList1 = new List<IIVQTreeViewItem>();
    List<IIVQTreeViewItem> ivqTreeViewItemList2 = new List<IIVQTreeViewItem>();
    TxObjectList displayedSV = new TxObjectList();
    if (obj.Children.Count > 0)
    {
      CApIVQManager.CollectChildren(obj.Children[0], ivqTreeViewItemList1);
      ivqTreeViewItemList1.Add(obj.Children[0]);
      if (obj.Children[0].IVQObject != null)
        ((Collection<ITxObject>) displayedSV).Add(obj.Children[0].IVQObject);
    }
    if (obj.Children.Count > 1)
    {
      CApIVQManager.CollectChildren(obj.Children[1], ivqTreeViewItemList2);
      ivqTreeViewItemList2.Add(obj.Children[1]);
      if (obj.Children[1].IVQObject != null)
        ((Collection<ITxObject>) displayedSV).Add(obj.Children[1].IVQObject);
    }
    dict.Add(ivqObject, CApIVQManager.INTERFERENCE_VOLUME_COLOR);
    List<TxNote> possibleNotes = (List<TxNote>) null;
    if (!CApIVQManager.createdNotes.TryGetValue((ITxObject) ivqObject, out possibleNotes))
      possibleNotes = new List<TxNote>();
    CApIVQManager.AddObjectsIntoDictWithColor(ivqTreeViewItemList1, dict, CApIVQManager.SWEPT_VOLUME1_HIERARCHY_COLOR, possibleNotes, CApIVQManager.SWEPT_VOL1_NOTES_COLOR);
    CApIVQManager.AddObjectsIntoDictWithColor(ivqTreeViewItemList2, dict, CApIVQManager.SWEPT_VOLUME2_HIERARCHY_COLOR, possibleNotes, CApIVQManager.SWEPT_VOL2_NOTES_COLOR);
    if (CApIVQManager.currentHighLightedIV != ((ITxObject) ivqObject).Id)
    {
      CApIVQManager.StopHighLighting();
      CApIVQManager.GetBlankAndDisplayNecessaryObjects(displayedSV, ivqObject);
      CApIVQManager.objUtils.EmphasizeObjects(dict, CApIVQManager.EMPHASIZE_PRIORITY);
      TxApplication.RefreshDisplay();
      CApIVQManager.currentHighLightedIV = ((ITxObject) ivqObject).Id;
    }
    Cursor.Current = current;
  }

  public static void StopHighLighting()
  {
    if (((Collection<ITxObject>) CApIVQManager.blankedObjects).Count > 0)
    {
      TxGraphicsUtilitiesEx.DisplayObjects(CApIVQManager.blankedObjects, true);
      ((Collection<ITxObject>) CApIVQManager.blankedObjects).Clear();
    }
    if (((Collection<ITxObject>) CApIVQManager.displayedObjects).Count > 0)
    {
      TxGraphicsUtilitiesEx.BlankObjects(CApIVQManager.displayedObjects, true);
      ((Collection<ITxObject>) CApIVQManager.displayedObjects).Clear();
    }
    CApIVQManager.currentHighLightedIV = "";
    CApIVQManager.objUtils.StopEmphasizeObjects();
  }

  public static void ChangeSelection(DnProcessSimulateCommands.InterferenceVolumeQuery.Tree.TreeNode selectedObjs)
  {
    if ((selectedObjs.Tag as IIVQTreeViewItem).IVQObject == null)
      return;
    ITxObject ivqObject = (selectedObjs.Tag as IIVQTreeViewItem).IVQObject;
    TxSelection selection = TxApplication.ActiveDocument.Selection;
    TxObjectList txObjectList = new TxObjectList();
    ((Collection<ITxObject>) txObjectList).Add(ivqObject);
    selection.SetItems(txObjectList);
  }

  public static void RestoreLocationsVisibility()
  {
    if (((Collection<ITxObject>) CApIVQManager.locationsSnapshot).Count <= 0)
      return;
    TxGraphicsUtilitiesEx.BlankObjects(CApIVQManager.locationsSnapshot, true);
    ((Collection<ITxObject>) CApIVQManager.locationsSnapshot).Clear();
  }
}
